package editor;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;

import javax.swing.*;

import loading.ImageLoader;

public class TileDialog extends JDialog implements ActionListener
{
	private JButton loadImage;
	private JButton done;
	private JButton cancel;
	private JPanel panel;
	
	private JCheckBox occupied;
	
	private ImageLoader img;
	
	private String tileFile;
	private String tilesetName;
	
	public TileDialog( JFrame parent, String tilesetName )
	{
		super( parent, true );
		
		this.setSize( 200, 150 );
		
		loadImage = new JButton( "Load Image" );
		done = new JButton( "Done" );
		cancel = new JButton( "Cancel" );
		
		img = null;
		
		this.tilesetName = tilesetName;
		
		panel = new JPanel()
		{
			@Override
			public void paintComponent( Graphics g )
			{
				g.setColor( Color.white );
				g.fillRect( 0, 0, this.getWidth(), this.getHeight() );
				
				if( img != null )
					img.draw( g, AffineTransform.getTranslateInstance( 0, 0 ) );
			}
		};
		panel.setPreferredSize( new Dimension( 32, 32 ) );
		
		
		occupied = new JCheckBox( "Unpassable" );
		occupied.setSelected( false );

		GridBagLayout layout = new GridBagLayout();
		addComponent( loadImage, 	1, 1, 1, 1, layout );
		addComponent( panel, 		3, 1, 1, 1, layout );
		addComponent( occupied, 	2, 2, 1, 1, layout );
		addComponent( done, 		1, 3, 1, 1, layout );
		addComponent( cancel, 		3, 3, 1, 1, layout );
		
		loadImage.addActionListener( this );
		done.addActionListener( this );
		cancel.addActionListener( this );
		
		this.setLayout( layout );
		
		this.setVisible( true );
	}
	
	public String getTileFile()
	{
		return tileFile;
	}
	
	private void addComponent( Component c, int col, int row, int width, int height, GridBagLayout layout )
	{
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = col;
		gbc.gridy = row;
		gbc.gridwidth = width;
		gbc.gridheight = height;
		gbc.weightx = 100;
		gbc.weighty = 100;
		layout.setConstraints( c, gbc );
		gbc.insets = new Insets( 5, 5, 5, 5 );
		this.add( c );
	}
	
	public void actionPerformed( ActionEvent e ) 
	{
		Object o = e.getSource();
		
		if( o.equals( loadImage ) )
		{
			JFileChooser fc = new JFileChooser();
			fc.setCurrentDirectory( new File( "C:/Documents and Settings/Owner/Desktop/Projects/Level Editor/Tiles" ) );
			int returnVal = fc.showOpenDialog( this );
			
			if( returnVal == JFileChooser.APPROVE_OPTION )
			{
				img = new ImageLoader( fc.getSelectedFile().getAbsolutePath() );
				panel.repaint();
			}
		}
		else if( o.equals( done ) )
		{
			tileFile = (new Tile( img, tilesetName, occupied.isSelected() )).save();
			
			this.dispose();
		}
		else if( o.equals( cancel ) )
		{
			this.dispose();
		}
	}
}
